package com.opencee.common.security;

import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * 自定义权限对象序列化类
 *
 * @author yadu
 */
public class GrantedDateAuthorityDeserializer extends JsonDeserializer {

    @Override
    public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
        ObjectMapper mapper = (ObjectMapper) jp.getCodec();
        JsonNode jsonNode = mapper.readTree(jp);
        List<GrantedAuthority> grantedAuthorities = new LinkedList<>();

        Iterator<JsonNode> elements = jsonNode.elements();
        while (elements.hasNext()) {
            JsonNode next = elements.next();
            if (next.has("startTime")) {
                JsonNode authority = next.get("authority");
                JsonNode startTime = next.get("startTime");
                JsonNode endTime = next.get("endTime");
                grantedAuthorities.add(new GrantedDateAuthority(authority.asText(), startTime.isNull() ? null : DateUtil.parseDateTime(startTime.asText()).toJdkDate(), endTime.isNull() ? null : DateUtil.parseDateTime(endTime.asText()).toJdkDate()));
            } else {
                JsonNode authority = next.get("authority");
                grantedAuthorities.add(new SimpleGrantedAuthority(authority.asText()));
            }
        }
        return grantedAuthorities;
    }

}
